import { useState } from 'react';
import { FiEdit2, FiTrash2, FiCheckSquare, FiCalendar, FiClock } from 'react-icons/fi';
import { Button } from '@/components/ui/Button';
import { formatDate } from '@/lib/utils';
import { useStore, Plan } from '@/lib/hooks/useStore';
import { CheckInForm } from '@/components/forms/CheckInForm';
import { PlanForm } from '@/components/forms/PlanForm';

interface PlanCardProps {
  plan: Plan;
}

export function PlanCard({ plan }: PlanCardProps) {
  const { deletePlan, updatePlan, checkIns } = useStore();
  const [isEditMode, setIsEditMode] = useState(false);
  const [isCheckInMode, setIsCheckInMode] = useState(false);

  // 获取该计划的所有打卡记录
  const planCheckIns = checkIns.filter((checkIn) => checkIn.planId === plan.id);
  
  // 计算完成度
  const totalDays = plan.endDate
    ? Math.ceil((plan.endDate.getTime() - plan.startDate.getTime()) / (1000 * 60 * 60 * 24))
    : 0;
  
  const completedDays = new Set(
    planCheckIns.map((checkIn) => new Date(checkIn.date).toDateString())
  ).size;
  
  const progressPercentage = totalDays > 0 
    ? Math.min(Math.round((completedDays / totalDays) * 100), 100)
    : 0;

  const handleDelete = () => {
    if (window.confirm('确定要删除这个计划吗?')) {
      deletePlan(plan.id);
    }
  };

  const toggleCompletion = () => {
    updatePlan(plan.id, { isCompleted: !plan.isCompleted });
  };

  if (isEditMode) {
    return (
      <div className="bg-white rounded-lg shadow-md p-4 mb-4">
        <h3 className="text-lg font-semibold mb-4">编辑计划</h3>
        <PlanForm
          initialData={{
            id: plan.id,
            title: plan.title,
            description: plan.description,
            startDate: plan.startDate,
            endDate: plan.endDate,
          }}
          onSuccess={() => setIsEditMode(false)}
        />
      </div>
    );
  }

  return (
    <div className="bg-white rounded-lg shadow-md p-4 mb-4">
      <div className="flex justify-between items-start">
        <div>
          <h3 className="text-lg font-semibold mb-1">
            {plan.title}
            {plan.isCompleted && (
              <span className="ml-2 text-xs bg-green-100 text-green-800 py-1 px-2 rounded">
                已完成
              </span>
            )}
          </h3>
          
          {plan.description && (
            <p className="text-gray-600 mb-3">{plan.description}</p>
          )}
          
          <div className="flex flex-col space-y-1 text-sm text-gray-500 mb-3">
            <div className="flex items-center">
              <FiCalendar className="mr-2" />
              <span>开始: {formatDate(plan.startDate)}</span>
            </div>
            
            {plan.endDate && (
              <div className="flex items-center">
                <FiCalendar className="mr-2" />
                <span>结束: {formatDate(plan.endDate)}</span>
              </div>
            )}
            
            <div className="flex items-center">
              <FiClock className="mr-2" />
              <span>打卡进度: {completedDays}/{totalDays > 0 ? totalDays : '未设置'} 天</span>
            </div>
          </div>
          
          {/* 进度条 */}
          {totalDays > 0 && (
            <div className="w-full bg-gray-200 rounded-full h-2.5 mb-4">
              <div
                className="bg-blue-600 h-2.5 rounded-full"
                style={{ width: `${progressPercentage}%` }}
              ></div>
            </div>
          )}
        </div>
        
        <div className="flex space-x-2">
          <Button
            variant="outline"
            size="icon"
            onClick={() => setIsEditMode(true)}
            aria-label="编辑"
          >
            <FiEdit2 className="h-4 w-4" />
          </Button>
          
          <Button
            variant="outline"
            size="icon"
            onClick={handleDelete}
            aria-label="删除"
          >
            <FiTrash2 className="h-4 w-4" />
          </Button>
          
          <Button
            variant={plan.isCompleted ? 'outline' : 'primary'}
            size="icon"
            onClick={toggleCompletion}
            aria-label={plan.isCompleted ? '标记为未完成' : '标记为完成'}
          >
            <FiCheckSquare className="h-4 w-4" />
          </Button>
        </div>
      </div>
      
      {isCheckInMode ? (
        <div className="mt-4 border-t pt-4">
          <h4 className="text-md font-medium mb-3">今日打卡</h4>
          <CheckInForm
            planId={plan.id}
            onSuccess={() => setIsCheckInMode(false)}
          />
        </div>
      ) : (
        <div className="mt-4 flex">
          <Button
            variant="primary"
            onClick={() => setIsCheckInMode(true)}
            className="w-full"
          >
            打卡
          </Button>
        </div>
      )}
      
      {/* 打卡记录列表 */}
      {planCheckIns.length > 0 && (
        <div className="mt-4 border-t pt-4">
          <h4 className="text-md font-medium mb-2">打卡记录 ({planCheckIns.length})</h4>
          <div className="space-y-3 max-h-60 overflow-y-auto">
            {planCheckIns
              .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
              .map((checkIn) => (
                <div key={checkIn.id} className="bg-gray-50 p-3 rounded">
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-700 font-medium">
                      {formatDate(checkIn.date)}
                    </span>
                  </div>
                  
                  {checkIn.note && (
                    <p className="text-sm text-gray-600 mt-1">{checkIn.note}</p>
                  )}
                  
                  {checkIn.imageUrl && (
                    <div className="mt-2">
                      <img
                        src={checkIn.imageUrl}
                        alt="打卡照片"
                        className="h-32 w-auto object-cover rounded"
                      />
                    </div>
                  )}
                </div>
              ))}
          </div>
        </div>
      )}
    </div>
  );
} 